package com.project.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.project.bean.UserBean;

import java.util.Date;
import java.util.HashMap;

public class JwtUtil {
    private static final long EXPIRE_TIME = 1000 * 60 * 15;
    //TOKEN_SECRET用于加密openid
    private static final String TOKEN_SECRET = "dm30dadbpzies95y2rq2ymtdhcz4h3u8";

    public static String createToken(UserBean userBean) {
        //过期时间
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        //私钥及加密算法
        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
        //设置头信息
        HashMap<String, Object> header = new HashMap<>(2);
        header.put("typ", "JWT");
        header.put("alg", "HS256");
        //附带username和userID生成签名
        String token = JWT.create().withHeader(header)
                .withClaim("userCode", userBean.getUserCode())
                .withClaim("openid", userBean.getOpenid())
                .withExpiresAt(date).sign(algorithm);
        return token;
    }


    /**
     * 认证
     *
     * @param token
     * @return
     */
    public static UserBean verifierJwt(String token) {
        //私钥及加密算法
        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
        UserBean userBean = null;
        JWTVerifier verifier = JWT.require(algorithm).build();
        try {
            //如果验证不成功会抛出异常
            DecodedJWT jwt = verifier.verify(token);
            userBean = new UserBean();
            userBean.setUserCode(jwt.getClaim("userCode").asString());
            userBean.setOpenid(jwt.getClaim("openid").asString());
        } catch (Exception e) {
            return userBean;
        }
        return userBean;
    }
}
